<template>
    <div>
        <FYNavBar :title="title"></FYNavBar>
        <van-address-edit
                :area-list="areaList"
                show-delete
                show-set-default
                show-search-result
                :address-info="addressInfo"
                :search-result="searchResult"
                :area-columns-placeholder="['请选择', '请选择', '请选择']"
                @save="onSave"
                @delete="onDelete"
                @change-detail="onChangeDetail"
        />
    </div>
</template>

<script>

import {ref} from "vue";
import {showToast} from "vant";
import {areaList} from "@vant/area-data";
import FYNavBar from "@/components/common/FYNavBar.vue";
import Address from "@/utils/address";

export default {
    name: "FVAddressEdit",
    components: {FYNavBar},
    setup() {
        const searchResult = ref([]);

        const onSave = () => showToast('save');
        const onDelete = () => showToast('delete');
        const onChangeDetail = (val) => {
            if (val) {
                searchResult.value = [
                    {
                        name: '黄龙万科中心',
                        address: '杭州市西湖区',
                    },
                ];
            } else {
                searchResult.value = [];
            }
        };

        return {
            onSave,
            onDelete,
            areaList,
            searchResult,
            onChangeDetail,
        };
    },
    data() {
        return {
            addressInfo: {},
            list : []
        }
    },
    methods: {
        onSave(content) {
            const address = Address.convertToServer(content);
            if (!this.isEdit) {
                this.$http.post(`address`, address).then(resp => {
                    if(resp.status === 201){
                        this.$message.success('添加成功')
                    }
                    this.$router.back();
                })
            }else {
                this.$http.put(`address/${this.addressInfo.id}`,address).then(resp => {
                    if(resp.status === 200){
                        this.$message.success('修改成功')
                        this.$router.back()
                    }
                })
            }

        },
        onEdit() {

        }
    },
    mounted() {
        if (this.isEdit) {
            this.addressInfo = this.$store.state.editingAddress;
        } else {
            this.$store.commit('clearEditingAddress')
        }
    },
    computed: {
        title() {
            return this.$route.name === 'address_edit' ? '编辑地址' : '添加地址';
        },
        isEdit() {
            return this.$route.name === 'address_edit';
        }
    }
}
</script>

<style scoped>

</style>
